package com.company.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import com.company.project.common.config.DcicUrlProperties;
import com.company.project.common.exception.BusinessException;
import com.company.project.common.exception.code.BaseResponseCode;
import com.company.project.common.utils.Constant;
import com.company.project.common.utils.DataResult;
import com.company.project.common.utils.EnumAreaType;
import com.company.project.common.utils.PasswordUtils;
import com.company.project.entity.MatchProjectEntity;
import com.company.project.entity.SysUser;
import com.company.project.entity.TeamUserEntity;
import com.company.project.service.MatchProjectService;
import com.company.project.service.TeamUserService;
import com.company.project.vo.req.TeamUser;
import com.company.project.vo.req.UserInTeamDTO;

/**
 * 团队-用户表
 *
 * @author ls
 * @email *****@mail.com
 * @date 2021-02-02 20:34:19
 */
@Controller
@RequestMapping("/")
@Api(tags = "比赛队伍用户模块")
@EnableConfigurationProperties(DcicUrlProperties.class)
public class TeamUserController extends BaseController{
    @Autowired
    private TeamUserService teamUserService;
    
    @Autowired
    private MatchProjectService matchProjectService;
    
    @Autowired
    private DcicUrlProperties dcicUrlProperties;

    /*************************前端展示***********************************/  
    @ApiOperation(value = "新增")
    @PostMapping("teamUser/add")
    @RequiresPermissions("teamUser:front:add")
    @ResponseBody
    public DataResult add(@RequestBody UserInTeamDTO dto){
    	//比赛报名是否开启
    	if(getMatchStatus()) {
    		TeamUserEntity teamUser = getCurrentTeamUser();
    		if(teamUser.getIsCaptain().equals(Constant.IS_TRUE)) {
    			//判断是否注册过
    			if(!PasswordUtils.isRegistered(dto.getName(), dto.getIdNumber(), dcicUrlProperties.getUrl())) {
    				throw new BusinessException("成员"+dto.getName()+"未在数字中国创新赛平台上注册，或者填写信息错误，请核查！");
    			}
    	    	TeamUserEntity entity = new TeamUserEntity();
    	    	BeanUtils.copyProperties(dto, entity);
    	    	entity.setDcicUserId(PasswordUtils.getMD5(dto.getName(), dto.getIdNumber()));
    	    	entity.setTeamId(teamUser.getTeamId());
    	    	entity.setIsCaptain(Constant.IS_FALSE);
    	        teamUserService.addTeamUser(entity);
    		}else {
    			throw new BusinessException(BaseResponseCode.FORBIDDEN);
    		}  	
            return DataResult.success();
    	}else {
			throw new BusinessException(BaseResponseCode.MATCH_STATUS_STOP);
		}
		
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("teamUser/delete/{id}")
    @RequiresPermissions("teamUser:front:delete")
    @ResponseBody
    public DataResult delete(@PathVariable ("id") String id){
    	//比赛报名是否开启
    	if(getMatchStatus()) {
    		if(isCaptain()) {
        		TeamUserEntity teamUser = teamUserService
        				.getOne(Wrappers.<TeamUserEntity>lambdaQuery().eq(TeamUserEntity::getId, id));
        		if (teamUser == null) {
        			throw new BusinessException(BaseResponseCode.NO_TEAM);
        		}
        		if (teamUser.getIsCaptain().equals(Constant.IS_TRUE)) {
        			throw new BusinessException("禁止删除队长！");
        		}
                teamUserService.removeById(id);
        	}else {
    			throw new BusinessException(BaseResponseCode.FORBIDDEN);
    		}    	
            return DataResult.success();
    	}else {
			throw new BusinessException(BaseResponseCode.MATCH_STATUS_STOP);
		}
    	
    }

    @ApiOperation(value = "更新")
    @PutMapping("teamUser/update")
    @RequiresPermissions("teamUser:front:update")
    @ResponseBody
    public DataResult update(@RequestBody UserInTeamDTO userInTeam){
    	//比赛报名是否开启
    	if(getMatchStatus()) {
    		if(isCaptain()) {
        		//判断是否全部注册过
        		if (!PasswordUtils.isRegistered(userInTeam.getName(), userInTeam.getIdNumber(), dcicUrlProperties.getUrl())) {
        			throw new BusinessException("成员" + userInTeam.getName() + "未在数字中国创新赛平台上注册，或者填写信息错误，请核查！");
        		}
        		if (StringUtils.isEmpty(userInTeam.getId())) {
        			throw new BusinessException("请核查输入ID！");
        		}
        		TeamUserEntity teamuser = teamUserService
        				.getOne(Wrappers.<TeamUserEntity>lambdaQuery().eq(TeamUserEntity::getId, userInTeam.getId()));
        		BeanUtils.copyProperties(userInTeam, teamuser);
        		teamuser.setDcicUserId(PasswordUtils.getMD5(teamuser.getName(), teamuser.getIdNumber()));
                teamUserService.updateById(teamuser);
        	}else {
    			throw new BusinessException(BaseResponseCode.FORBIDDEN);
    		}    	
            return DataResult.success();
    	}else {
			throw new BusinessException(BaseResponseCode.MATCH_STATUS_STOP);
		}
    	
    }
    
    /*************************后端展示***********************************/
    
    /**
    * 跳转到页面
    */
    @GetMapping("/index/teamUser")
    public String teamUser() {
        return "teamuser/list";
    }
    
    /**
     * 跳转到页面
     */
     @GetMapping("/index/teamUserLastDay")
     public String teamUserLastDay() {
         return "teamuser/listLastDay";
     }

		/*@ApiOperation(value = "新增")
		@PostMapping("teamUser/add")
		@RequiresPermissions("teamUser:add")
		@ResponseBody
		public DataResult add(@RequestBody TeamUserEntity teamUser){
		    teamUserService.save(teamUser);
		    return DataResult.success();
		}
		
		@ApiOperation(value = "删除")
		@DeleteMapping("teamUser/delete")
		@RequiresPermissions("teamUser:delete")
		@ResponseBody
		public DataResult delete(@RequestBody @ApiParam(value = "id集合") List<String> ids){
		    teamUserService.removeByIds(ids);
		    return DataResult.success();
		}
		
		@ApiOperation(value = "更新")
		@PutMapping("teamUser/update")
		@RequiresPermissions("teamUser:update")
		@ResponseBody
		public DataResult update(@RequestBody TeamUserEntity teamUser){
		    teamUserService.updateById(teamUser);
		    return DataResult.success();
		}*/

	@SuppressWarnings("rawtypes")
	@ApiOperation(value = "查询分页数据")
    @PostMapping("teamUser/listByPage")
    @RequiresPermissions("teamUser:list")
    @ResponseBody
    public DataResult findListByPage(@RequestBody TeamUserEntity teamUser){
		
		SysUser currentUser = getCurrentUser();		
		String username = currentUser.getUsername();		
		String area = EnumAreaType.getIndexByCode(username);
		
		//添加日期筛选
		if (!StringUtils.isEmpty(teamUser.getStartTime()) &&!StringUtils.isEmpty(teamUser.getEndTime())) {
			LambdaQueryWrapper<MatchProjectEntity> projectWrapper = Wrappers.lambdaQuery();
		    //查询条件示例
		    //queryWrapper.eq(MatchProjectEntity::getId, matchProject.getId());	    		    	        
	        projectWrapper.ge(MatchProjectEntity::getUpdateTime, teamUser.getStartTime());
	        projectWrapper.lt(MatchProjectEntity::getUpdateTime, teamUser.getEndTime());
	        
			List<MatchProjectEntity> projects = matchProjectService.list(projectWrapper);
			if(projects!=null&&projects.size()>0) {
				List<String> teamIds=projects.stream().map(MatchProjectEntity::getTeamId).collect(Collectors.toList());
				
				Page page = new Page(teamUser.getPage(), teamUser.getLimit());       
		        IPage<TeamUser> users = teamUserService.getListLastDay(page,teamIds,area);
		        return DataResult.success(users);
			}
			return DataResult.success();
        }
		//未添加日期筛选
        Page page = new Page(teamUser.getPage(), teamUser.getLimit());        
        //QueryWrapper<TeamUser> wrapper = new QueryWrapper<>();        
        IPage<TeamUser> users = teamUserService.getList(page,area);
        return DataResult.success(users);
    }
	
	@SuppressWarnings("rawtypes")
	@ApiOperation(value = "查询分页数据")
    @PostMapping("teamUser/listByPageLastDay")
    @RequiresPermissions("teamUser:listLastDay")
    @ResponseBody
    public DataResult findListByPageLastDay(@RequestBody TeamUserEntity teamUser){
		SysUser currentUser = getCurrentUser();		
		String username = currentUser.getUsername();		
		String area = EnumAreaType.getIndexByCode(username);
		LambdaQueryWrapper<MatchProjectEntity> projectWrapper = Wrappers.lambdaQuery();
	    //查询条件示例
	    //queryWrapper.eq(MatchProjectEntity::getId, matchProject.getId());	    
	    Calendar calendar = Calendar.getInstance();//此时打印它获取的是系统当前时间         
        calendar.add(Calendar.DATE, -1);    //得到前一天
        String  yestedayDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
        String start = yestedayDate+" 00:00:00";
        String end = yestedayDate+" 23:59:59";
        projectWrapper.ge(MatchProjectEntity::getUpdateTime, start);
        projectWrapper.le(MatchProjectEntity::getUpdateTime, end);
		List<MatchProjectEntity> projects = matchProjectService.list(projectWrapper);
		if(projects!=null&&projects.size()>0) {
			List<String> teamIds=projects.stream().map(MatchProjectEntity::getTeamId).collect(Collectors.toList());
			
			Page page = new Page(teamUser.getPage(), teamUser.getLimit());       
	        IPage<TeamUser> users = teamUserService.getListLastDay(page,teamIds,area);
	        return DataResult.success(users);
		}
		return DataResult.success();
    }

}
